﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using Common.Utilities.Excel.Xml;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;

namespace Common.Utilities.Excel.Export
{
    public class DataFormat
    {
        /// <summary>
        /// 从配置中获取的DataFormatString, 
        /// 数据在Excel中的显示格式, 输入格式字符串如"0.00"或"yyyy/MM/dd", 如果不是Excel中的内置格式, 则会自动产生该格式
        /// </summary>
        public string DataFormatString { get; set; }
        /// <summary>
        /// 是否已经初试化数据格式
        /// </summary>
        private bool isInitDataFormat { get; set; }
        /// <summary>
        /// 已经创建的数据格式值
        /// </summary>
        protected short SDataFormat { get; set; }

        public CellStyle CellStyle{get;set;}

        public DataFormat(XmlNode dataFormatNode, CellStyle cellStyle)
        {
            DataFormatString = XmlUtility.getNodeAttributeStringValue(dataFormatNode, "dataformatstring", "");
            isInitDataFormat = false;
            SDataFormat = -1;
            CellStyle = cellStyle;
        }

        /// <summary>
        /// 把字体格式设置到单元格中
        /// </summary>
        /// <param name="workbook"></param>
        public void SetDataFormat(IWorkbook workbook)
        {
            SetDataFormat(CellStyle.Style, workbook);
        }

        /// <summary>
        /// 把字体格式设置到单元格中
        /// </summary>
        /// <param name="cellStyle"></param>
        /// <param name="workbook"></param>
        public void SetDataFormat(ICellStyle cellStyle, IWorkbook workbook)
        {
            if (!isInitDataFormat && !string.IsNullOrEmpty(DataFormatString))
            {
                // 如果不是内置, 则创建, 如果是内置, 就直接取内置的
                if (HSSFDataFormat.GetBuiltinFormat(DataFormatString) == -1)
                {
                    IDataFormat hssfDataFormat = workbook.CreateDataFormat();
                    SDataFormat = hssfDataFormat.GetFormat(DataFormatString);
                }
                else
                {
                    SDataFormat = HSSFDataFormat.GetBuiltinFormat(DataFormatString);
                }
            }
            cellStyle.DataFormat = SDataFormat;
        }


    }
}
